#include "protocol.hpp"
#include "Tcpserver.hpp"
#include "Calculate.hpp"
#include "Daemon.hpp"
#include <iostream>
#include <memory>
#include <unistd.h>

using namespace Net_Work;
using namespace Protocol;
using namespace CalculateNS;

// 网络负责IO发送
// HandlerRequest字节流数据解析和调用业务处理方法的
// 处理报文的方法

std::string HandlerRequest(std::string& inbufferstream, bool* error_code)
{
    *error_code = true;
    //0.计算机对象
    Calculate cal;
    //1.构建响应对象
    std::unique_ptr<Factory> factory = std::make_unique<Factory>();
    auto req = factory->BuildRequest();
    std::string total_resp_string;
    std::string message;
    while(Decode(inbufferstream,&message))
    {
        std::cout<< message << "---- message" << std::endl;
        //3.读到了完整的报文，进行反序列化
        if(!req->DeSerialize(message))
        {
            std::cout<< "Deserialize error" << std::endl;
            *error_code = false;
            return std::string();

        }
        auto resp = cal.Cal(req);
        std::string send_string;
        resp->Serialize(&send_string);
        send_string = Encode(send_string);
        total_resp_string += send_string;
    }
    return total_resp_string;
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage :" << argv[0] << "serverport" << std::endl;
        return 1;
    }
    uint16_t localport = std::stoi(argv[1]);
    //Daemon(false, false);
    std::unique_ptr<Tcpserver> svr(new Tcpserver(localport, HandlerRequest));
    svr->loop();
    return 0;
}